package com.cd.javacxy.module.web.service.impl;

import com.cd.javacxy.common.model.entity.CxyBlog;
import com.cd.javacxy.common.model.enums.FileTopicType;
import com.cd.javacxy.common.model.enums.OrderByEnum;
import com.cd.javacxy.common.model.enums.PageSize;
import com.cd.javacxy.common.model.query.BlogQuery;
import com.cd.javacxy.common.model.query.UpdateQuery4ArticleCount;
import com.cd.javacxy.common.utils.Page;
import com.cd.javacxy.common.utils.PageResult;
import com.cd.javacxy.exception.BussinessException;
import com.cd.javacxy.module.web.dao.CxyBlogDao;
import com.cd.javacxy.module.web.service.CxyAttachmentService;
import com.cd.javacxy.module.web.service.CxyBlogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * CxyBlog的服务接口的实现类
 *
 * @author yanghy
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CxyBlogServiceImpl implements CxyBlogService {

    private final CxyBlogDao cxyBlogDao;

    private final CxyAttachmentService attachmentService;

    @Override
    public PageResult<CxyBlog> findBlogByPage(BlogQuery blogQuery) {
        int count = this.cxyBlogDao.selectCount(blogQuery);
        int pageSize = PageSize.PAGE_SIZE20.getSize();
        int pageNum = blogQuery.getPageNum();
        Page page = new Page(pageNum, count, pageSize);
        blogQuery.setPage(page);
        blogQuery.setOrderBy(OrderByEnum.CREATE_TIME_DESC);
        List<CxyBlog> list = this.cxyBlogDao.selectList(blogQuery);
        return new PageResult<>(page, list);
    }

    @Override
    public CxyBlog showBlog(Integer blogId) throws BussinessException {
        CxyBlog blog = this.getBlog(blogId);
        if (blog == null) {
            throw new BussinessException("文章不存在,或已删除");
        }
        blog.setAttachment(this.attachmentService.getAttachmentByTopicIdAndFileType(blog.getBlogId(), FileTopicType.BLOG));
        UpdateQuery4ArticleCount updateQuery4ArticleCount = new UpdateQuery4ArticleCount();
        updateQuery4ArticleCount.setAddReadCount(Boolean.TRUE);
        updateQuery4ArticleCount.setArticleId(blogId);
        this.cxyBlogDao.updateInfoCount(updateQuery4ArticleCount);
        return blog;
    }

    public CxyBlog getBlog(Integer blogId) {
        if (blogId == null) {
            return null;
        }
        BlogQuery blogQuery = new BlogQuery();
        blogQuery.setBlogId(blogId);
        blogQuery.setShowContent(Boolean.TRUE);
        List<CxyBlog> list = this.cxyBlogDao.selectList(blogQuery);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }
}